<?php
/**
 * BootStrap
 *
 *
 * @version $Id: Bootstrap.php 123 2010-04-19 08:07:13Z hami $
 * @license New BSD License
 * @uses Zend_Application_Bootstrap_Bootstrap
 * @package core
 * @subpackage Bootstrap
 */
class Bootstrap extends Zend_Application_Bootstrap_Bootstrap
{
    static private $_paths;
    static public $config;

    // TODO INSTALL
    protected function _initInstallChecker()
    {

        $config = Sfs_Core_Config::getConfig();
        if (null == $config->production->install || null == $config->production->install->date) {
            header('Location: install.php');
            exit;
        }
    }

    protected function _initConfig()
    {

        // reference http://framework.zend.com/manual/en/performance.classloading.html
        $appBootstrap = $this->getApplication()->getOptions();
        self::$config = $appBootstrap;

        $enablePluginLoaderCache = $this->getOption('enablepluginloadercache');
        $classFileIncCache = APPLICATION_PATH.'/../data/pluginLoaderCache.php';

        if (file_exists($classFileIncCache)) {
            include_once $classFileIncCache;
        }
        if ($enablePluginLoaderCache) {
            Zend_Loader_PluginLoader::setIncludeFileCache($classFileIncCache);
        }

    }

    protected function _initSesion()
    {
        Zend_Session::setOptions(array(
           /* SSL server */ 'cookie_secure' => true,
        //     /* own name */ 'name' => 'mySSL',
        /* own storage */ 'save_path' => APPLICATION_PATH.'/../data/session',
        /* XSS hardening */ 'cookie_httponly' => true,
        /* short lifetime */ 'gc_maxlifetime' => 15 * 60
        ));
    }




    protected function _initDefaultTimezone()
    {
        date_default_timezone_set(self::$config['default_timezone']);
    }

    protected function _initControllerHelper()
    {
        Zend_Controller_Action_HelperBroker::addPrefix('Sfs_Controller_Action_Helper');

    }

    protected function _initComputePaths()
    {
        self::$_paths['config']        = APPLICATION_PATH . '/config';
        self::$_paths['library']     = realpath(APPLICATION_PATH . '/../library');
        self::$_paths['modules']     = realpath(APPLICATION_PATH . '/modules');
        self::$_paths['data']        = realpath(APPLICATION_PATH . '/../data');
        self::$_paths['cache']      =  realpath(APPLICATION_PATH . '/../cache');
        self::$_paths['tmp']        = realpath(APPLICATION_PATH . '/../tmp');
        self::$_paths['document']        = realpath(APPLICATION_PATH . '/../public');
        //$this->_paths['layout']        = $this->_paths['core_path'] . '/public/themes';
        self::$_paths['fonts']        = realpath(APPLICATION_PATH . '/../fonts');

    }



    static public function getPath($key='')
    {
        if ($key <>'')
        return self::$_paths[$key];
        else
        return self::$_paths;
    }

    protected function _initCache()
    {
        $frontendOptions = array(
        'lifetime' => 7200, // cache lifetime of 2 hours
        'automatic_serialization' => true
        );

        $backendOptions = array(
        'cache_dir' =>  self::getPath('cache')
        );
        // getting a Zend_Cache_Core object
        $cache = Zend_Cache::factory('Core', 'File', $frontendOptions, $backendOptions);
        Zend_Registry::set('cache',$cache);
    }

    public function _initLogger()
    {
        $logger = new Zend_Log();
        //TODO application.ini 安裝方式更改後 再將判斷加上
        // if ('staging' == APPLICATION_ENV) {
        $writer = new Zend_Log_Writer_Stream(self::$_paths['cache'].'/web.log');
        $logger->addWriter($writer);
        //     }
        // TODO Firebug test
        //$writer = new Zend_Log_Writer_Firebug();
        //$logger->addWriter($writer);

        //Enable log
        if ('development' == APPLICATION_ENV) {
            $text_writer = new Zend_Log_Writer_Firebug();
            $logger->addWriter($text_writer);
        }
        // 註冊 logger
        Zend_Registry::set('logger', $logger);
    }

    public function _initDoctrine()
    {

        require_once 'Doctrine.php';
        $loader = Zend_Loader_Autoloader::getInstance();
        $loader->pushAutoloader(array('Doctrine', 'autoload'));

        $doctrineConfig = $this->getOption('doctrine');

        $manager = Doctrine_Manager::getInstance();

        //   $manager->setAttribute(Doctrine::ATTR_AUTO_ACCESSOR_OVERRIDE, true);
        $manager->setAttribute(
        Doctrine::ATTR_MODEL_LOADING,
        Doctrine::MODEL_LOADING_CONSERVATIVE);
        $manager->setAttribute(Doctrine::ATTR_AUTOLOAD_TABLE_CLASSES,true);


        // Add models and generated base classes to Doctrine autoloader
        // Doctrine::loadModels($doctrineConfig['models_path']);

        $conn = $manager->openConnection($doctrineConfig['connection_string']);
        $conn->setCharset('utf8');
        $conn->setAttribute(Doctrine::ATTR_USE_NATIVE_ENUM, true);

        return $conn;
    }

    protected function _initDoctrineCli()
    {

        if ('testing' == APPLICATION_ENV || empty($_SERVER['argv'])) {
            return;
        }


        $options = array(
            'data_fixtures_path' => APPLICATION_PATH . '/doctrine/data/fixtures',
            'models_path'        => APPLICATION_PATH . '/doctrine/models',
            'migrations_path'    => APPLICATION_PATH . '/doctrine/data/migrations',
            'sql_path'           => APPLICATION_PATH . '/doctrine/data',
            'yaml_schema_path'   => APPLICATION_PATH . '/doctrine/data/schema/schma.yml',
        'generate_models_options' => array(
        'pearStyle' => false,
        //        'generateTableClasses' => true,
        'generateBaseClasses' => true,
        'classPrefixFiles' => false,
        'baseClassPrefix' => 'Base',
        //  'classPrefix' => 'Application_Model_',
        'baseClassesDirectory' => null,
        )
        );

        $manager = $this->bootstrap('doctrine')->getResource('doctrine');
        $manager->setAttribute(Doctrine::ATTR_MODEL_LOADING,
        Doctrine::MODEL_LOADING_AGGRESSIVE);

        return new Doctrine_Cli($options);
    }

    //    protected function _initDb()
    //    {
    //        $this->bootstrap('DefaultModuleAutoloader');
    //        //$config   = new Zend_Config($options);
    //        $config = self::$config['resources']['db'];
    //        //        //			echo "<pre>";print_r($config);exit;
    //
    //        //        $profiler = new Zend_Db_Profiler_Firebug('All DB Queries');
    //        $db       = Zend_Db::factory($config['adapter'],$config['params']);
    //        //
    //        //        $profiler->setEnabled($config->profiler->enabled);
    //        //        $db->setProfiler($profiler);
    //        Zend_Db_Table_Abstract::setDefaultAdapter($db);
    //
    //
    //    }

    public function _initControllerPlugins()
    {

        Zend_Controller_Front::getInstance()
        ->registerPlugin(new Sfs_Controller_Plugin_Ssl(TRUE))
        ->registerPlugin(new Sfs_Controller_Plugin_Auth() )
        ->registerPlugin(new Sfs_ModuleConfig())
        ->registerPlugin(new Sfs_Http_Conditional())

        ;

    }


    protected function _initDefaultModuleAutoloader()

    {

        $this->bootstrap('frontController');
        $front = $this->frontController;
        $autoloader = Zend_Loader_Autoloader::getInstance();

        $modules = $front->getControllerDirectory();

        $default = $front->getDefaultModule();
        foreach (array_keys($modules) as $module) {
            $autoloader->pushAutoloader(new Zend_Application_Module_Autoloader(array(
                'namespace' => ucwords($module),
                'basePath' => $front->getModuleDirectory($module),
            )));
        }

    }


    function _initViewHelpers()
    {
        $config = $this->getOptions(); // 設定檔
        $front = $this->frontController;
        $this->bootstrap('layout');
        $layout = $this->getResource('layout');

        $view = $layout->getView();

        // 取得網頁基本路徑
        $view->baseUrl = $front->getBaseUrl();

        // 取得程式URL 的絕對路徑
        //$view->baseScript = $view->baseUrl.'/'. $this->_request->getModuleName().'/'.$this->_request->getControllerName();
        $view->config = $config;

        // 取得 認證
        $auth = Zend_Auth::getInstance();
        //  取得是否通過認證
        $view->authenticated = $auth->hasIdentity();

        $view->addHelperPath('Sfs/View/Helper', 'Sfs_View_Helper');

        $view->doctype('XHTML1_STRICT');
        $view->headMeta()->appendHttpEquiv('Content-Type', 'text/html;charset=utf-8');

    }

}

